package com.yami.shop.rights.common.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.enums.ShopWalletAmountType;
import com.yami.shop.bean.enums.ShopWalletChangeReason;
import com.yami.shop.bean.model.ShopWalletLog;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.PoiExcelUtil;
import com.yami.shop.rights.common.dao.RightsExternalMapper;
import com.yami.shop.rights.common.dto.ProdRightsDto;
import com.yami.shop.rights.common.dto.RightsExternalExcelDto;
import com.yami.shop.rights.common.model.ProdRights;
import com.yami.shop.rights.common.model.ProdRightsExternalData;
import com.yami.shop.rights.common.model.RightsExternal;
import com.yami.shop.rights.common.service.ProdRightsExternalDataService;
import com.yami.shop.rights.common.service.ProdRightsService;
import com.yami.shop.rights.common.service.RightsExternalService;
import com.yami.shop.service.UserService;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RightsExternalServiceImpl extends ServiceImpl<RightsExternalMapper, RightsExternal> implements RightsExternalService {

    @Autowired
    private RightsExternalMapper rightsExternalMapper;
    @Autowired
    private ProdRightsExternalDataService prodRightsExternalService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProdRightsService rightsService;

    @Override
    public IPage<RightsExternal> pageList(PageParam<RightsExternal> page, ProdRightsDto vo) {
        QueryWrapper<RightsExternal> prodRightsQueryWrapper = new QueryWrapper<>();
        prodRightsQueryWrapper.eq("shop_id", vo.getShopId());
        prodRightsQueryWrapper.like(ObjectUtil.isNotEmpty(vo.getRightsName()),"name", vo.getRightsName());
        prodRightsQueryWrapper.orderByDesc("create_time");
        // -1 为删除权益状态
        prodRightsQueryWrapper.ne("status", -1);
        PageParam<RightsExternal> rightsExternalPageParam = rightsExternalMapper.selectPage(page, prodRightsQueryWrapper);
        // 补充 使用个数，核销个数
        for (RightsExternal record : rightsExternalPageParam.getRecords()) {
            QueryWrapper<ProdRightsExternalData> prodRightsExternalDataQueryWrapper = new QueryWrapper<>();
            prodRightsExternalDataQueryWrapper.eq("external_id",record.getId());
            List<ProdRightsExternalData> list =
                    prodRightsExternalService.list(prodRightsExternalDataQueryWrapper);
            // 使用个数
            record.setUseCount(list.stream().filter(s->s.getStatus() == 1 || s.getStatus() == 2).count());
            // 核销个数
            record.setWriteOffCount(list.stream().filter(s->s.getStatus() == 2).count());
        }
        return rightsExternalPageParam;
    }

    @Override
    public void excelExternal(Long id, HttpServletResponse response) {
        List<RightsExternalExcelDto> rightsExternalExcelDtos = prodRightsExternalService.excelExternalRecord(id);
        // 获取核销人手机号
        Set<String> collect = rightsExternalExcelDtos.stream().filter(s->ObjectUtil.isNotEmpty(s.getHolderUserId())).map(RightsExternalExcelDto::getHolderUserId).collect(Collectors.toSet());
        Map<String,String> holderUserMap = new HashMap<>();
        collect.forEach(s->{
            User userDetail = userService.getUserDetail(s);
            holderUserMap.put(s,userDetail.getUserMobile());
        });
        boolean isCn = I18nMessage.getDbLang().equals(LanguageEnum.LANGUAGE_ZH_CN.getLang());
        ExcelWriter writer = ExcelUtil.getBigWriter();
        List<String> headerList;
        String[] headerCn = {"序号","CODE","状态","使用人手机号","核销人手机号"};
        String[] headerEn = {"Serial Number","CODE","status","use CallPhone","holder UserCallPhone"};
        headerList = Arrays.asList(isCn ? headerCn : headerEn);
        writer.merge(headerList.size() - 1, I18nMessage.getMessage("yami.shop.external.log.excel"));
        writer.writeRow(headerList);
        Sheet sheet = writer.getSheet();
        for (int i = 1; i < headerList.size(); i++) {
            sheet.setColumnWidth(i, 20 * 256);
        }
        int row = 1;
        for (RightsExternalExcelDto rightsExternalExcelDto : rightsExternalExcelDtos) {
            int firstRow = ++row;
            int col = -1;
            PoiExcelUtil.mergeIfNeed(writer, firstRow, firstRow, ++col, col, row - 1);
            PoiExcelUtil.mergeIfNeed(writer, firstRow, firstRow, ++col, col, rightsExternalExcelDto.getCode());
            PoiExcelUtil.mergeIfNeed(writer, firstRow, firstRow, ++col, col, rightsExternalExcelDto.getStatus() == 0 ? "未发放" : (rightsExternalExcelDto.getStatus() == 1 ? "已发放" : "核销"));
            PoiExcelUtil.mergeIfNeed(writer, firstRow, firstRow, ++col, col, rightsExternalExcelDto.getUseCallPhone());
            PoiExcelUtil.mergeIfNeed(writer, firstRow, firstRow, ++col, col, holderUserMap.get(rightsExternalExcelDto.getHolderUserId()));
        }
        PoiExcelUtil.writeExcel(response, writer);
    }

    @Override
    public List<RightsExternal> getDataListByRithsIds(String rightsId) {
        if(ObjectUtil.isEmpty(rightsId)){
            return null;
        }
        List<String> rightsExternalId = rightsService.list(new QueryWrapper<ProdRights>().in("id", Arrays.asList(rightsId.split(",")))).stream().map(s -> s.getProdId()).collect(Collectors.toList());

        QueryWrapper<RightsExternal> prodRightsQueryWrapper = new QueryWrapper<>();
        prodRightsQueryWrapper.in("id",rightsExternalId);
        prodRightsQueryWrapper.orderByDesc("create_time");
        // -1 为删除权益状态
        prodRightsQueryWrapper.ne("status", -1);
        List<RightsExternal> rightsExternals = rightsExternalMapper.selectList(prodRightsQueryWrapper);
        // 补充 使用个数，核销个数
        for (RightsExternal record : rightsExternals) {
            QueryWrapper<ProdRightsExternalData> prodRightsExternalDataQueryWrapper = new QueryWrapper<>();
            prodRightsExternalDataQueryWrapper.eq("external_id",record.getId());
            List<ProdRightsExternalData> list =
                    prodRightsExternalService.list(prodRightsExternalDataQueryWrapper);
            // 使用个数
            record.setUseCount(list.stream().filter(s->s.getStatus() == 1 || s.getStatus() == 2).count());
            // 核销个数
            record.setWriteOffCount(list.stream().filter(s->s.getStatus() == 2).count());
        }
        return rightsExternals;
    }
}
